package com.heima.app.gateway.filter;

import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component//过滤器自动生效
@Slf4j//自动打印日志
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.获取请求头里边的token信息
        String token = request.getHeaders().getFirst("token");

        //3.校验当前请求路径是不是登录接口
        //3.1当前请求什么接口
        //3.2是不是登录接口
        if (request.getPath().toString().contains("login")){//路径里含有login，所以是登录接口，可以放行
            //放行
            return chain.filter(exchange);
        }

        //4.判断token是否为空
        //StringUtils.isEmpty或者StringUtils.isBlank，两个一起用的，用来判空
        //isBlank用来判空外，还判断参数是否存在
        if (StringUtils.isEmpty(token)){

            //设置状态吗
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5.校验token有效性（JWT工具类）
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i==1||i==2){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //以上全部通过，放行
        return chain.filter(exchange);
    }
}
